import { LoadingButton } from '@mui/lab';
import {
    Box,
    Button,
    Dialog,
    DialogContent,
    DialogTitle,
    InputLabel,
    MenuItem,
    Select,
    SelectChangeEvent,
    Typography
} from '@mui/material';
import React, { useEffect, useState } from 'react';

import TokenManager, { Network, Token } from '../../api/token/token-manager';
import ParseCSVToTeam from '../../libs/parse-csv-to-team';
import PopupTransition from '../shared/dialogs/UIs/popup-transition';
import { useStyles } from '../shared/dialogs/UIs/styled-mui-dialog';
import { WhiteFormControl, WhiteTextField } from '../shared/forms';

export interface DisbursementPopupProps {
    show: boolean;
    onTransactionsUploaded: Function;
    onCloseDisbursementPopup: Function;
    tokens: Token[];
}

export default function DisbusementPopup(props: DisbursementPopupProps) {
    const [title, setTitle] = useState<string>(undefined);
    const [token, setToken] = useState('');
    const [network, setNetwork] = useState('');
    const [networkObj, setNetworkObj] = useState<Network>(null);
    const [networkOptions, setNetworkOptions] = useState<Network[]>([]);
    const [networkUp, setNetworkUp] = useState<boolean>(true);
    const [loading, setLoading] = useState<boolean>(false);
    const style = useStyles();

    useEffect(() => {
        if (props.tokens.length) {
            const token = props.tokens[0].token || 'SLP';
            setToken(token);
        }
    }, [props.tokens]);

    useEffect(() => {
        setNetwork('');
        if (!token || !props.tokens.length) {
            return;
        }
        const curr = props.tokens.find((it) => it.token === token);
        if (curr) {
            setNetworkOptions(curr.networks);
        }
    }, [token]);

    useEffect(() => {
        networkOptions?.length > 0 && setNetwork(networkOptions[0].id);
    }, [networkOptions]);

    useEffect(() => {
        const currObj = networkOptions.find((it) => it.id === network);
        setNetworkObj(currObj);
        const checkNetwork = async () => {
            setLoading(true);
            setNetworkUp(true);
            try {
                return await TokenManager.checkNetWorkUp(network);
            } catch (e) {
                console.error(e);
                setNetworkUp(false);
            } finally {
                setLoading(false);
            }
        };
        if (network) {
            checkNetwork().then((res) => setNetworkUp(res.up));
        }
    }, [network]);

    const onFileUpload = async (event) => {
        props.onTransactionsUploaded(title, token, networkObj, await ParseCSVToTeam.parse(event));
        event.target.value = null;
    };

    const onTitleChange = (event) => {
        setTitle(event.target?.value);
    };

    const onTokenSelected = (event: SelectChangeEvent<string>) => {
        setToken(event.target?.value);
    };

    const onNetworkSelected = async (event: SelectChangeEvent) => {
        const curr = event.target?.value;
        setNetwork(curr);
    };

    const onCancelClick = () => {
        props.onCloseDisbursementPopup();
    };

    const isTitleError = () => {
        return title !== undefined && typeof title === 'string' && title.trim() === '';
    };

    return (
        <div>
            <Dialog open={props.show} TransitionComponent={PopupTransition} fullWidth>
                <Box className={`${style.dialogBackground} ${style.center}`}>
                    <DialogTitle className={style.textTitle}>Add Disbursement</DialogTitle>
                </Box>
                <DialogContent className={`${style.dialogBackground} ${style.center}`}>
                    <Box sx={{ width: '100%' }}>
                        <WhiteTextField
                            label="Title"
                            variant="outlined"
                            onChange={onTitleChange}
                            fullWidth
                            value={title}
                            required={true}
                            error={isTitleError()}
                            placeholder={'Enter your disbursement title'}
                            autoFocus={true}
                        />

                        <WhiteFormControl className="top-30 w-100">
                            <InputLabel>Token</InputLabel>
                            <Select
                                label="Token"
                                value={token}
                                onChange={onTokenSelected}
                                disabled={!props.tokens?.length}
                            >
                                {props.tokens &&
                                    props.tokens.map(({ token, icon }) => (
                                        <MenuItem
                                            key={token}
                                            value={token}
                                            className={style.menuItem}
                                        >
                                            <Box
                                                component="img"
                                                sx={{
                                                    height: 20,
                                                    width: 20,
                                                    marginRight: '0.75rem'
                                                }}
                                                alt="Icon"
                                                src={icon}
                                            />
                                            {token}
                                        </MenuItem>
                                    ))}
                            </Select>
                        </WhiteFormControl>

                        <WhiteFormControl className="top-30 w-100">
                            <InputLabel>Network</InputLabel>
                            <Select
                                label="Network"
                                value={network}
                                onChange={onNetworkSelected}
                                disabled={!networkOptions?.length}
                            >
                                {networkOptions.map(({ icon, name, id }) => (
                                    <MenuItem key={id} value={id} className={style.menuItem}>
                                        <Box
                                            component="img"
                                            sx={{
                                                height: 20,
                                                width: 20,
                                                marginRight: '0.75rem'
                                            }}
                                            alt="Icon"
                                            src={icon}
                                        />
                                        {name}
                                    </MenuItem>
                                ))}
                            </Select>
                        </WhiteFormControl>

                        {!networkUp && (
                            <Typography
                                variant="h6"
                                align={'center'}
                                sx={{
                                    color: 'red',
                                    mt: 2,
                                    mb: -2
                                }}
                            >
                                {networkObj?.name} is down
                            </Typography>
                        )}

                        {!props.tokens?.length && (
                            <Typography
                                variant="h6"
                                align={'center'}
                                sx={{
                                    color: 'red',
                                    mt: 2,
                                    mb: -2
                                }}
                            >
                                No Token available
                            </Typography>
                        )}

                        {!networkOptions?.length && (
                            <Typography
                                variant="h6"
                                align={'center'}
                                sx={{
                                    color: 'red',
                                    mt: 2,
                                    mb: -2
                                }}
                            >
                                No Network available
                            </Typography>
                        )}

                        <LoadingButton
                            className="top-30 text-white"
                            variant="contained"
                            component="label"
                            size="large"
                            fullWidth
                            disabled={!title || !network || !networkUp}
                            loading={loading}
                        >
                            {!loading ? 'Upload CSV' : 'Checking Network'}
                            <input type="file" onChange={onFileUpload} hidden />
                        </LoadingButton>

                        <div className="text-center top-20">
                            <Button
                                variant="text"
                                onClick={onCancelClick}
                                className={'text-white'}
                                sx={{ '&:hover': { fontWeight: 500 } }}
                            >
                                Cancel
                            </Button>
                        </div>
                    </Box>
                </DialogContent>
            </Dialog>
        </div>
    );
}
